﻿using SD.IdentitySystem;
using SD.Infrastructure.Repository.EntityFramework;
using SD.Infrastructure.RepositoryBase;
using SD.OpcProxy.Domain.Entities;
using SD.OpcProxy.Domain.Mediators;
using SD.OpcProxy.ValueObjects;
using SD.OpcProxy.ValueObjects.Enums;

namespace SD.OpcProxy.Repository.Base
{
    /// <summary>
    /// 数据初始化器实现
    /// </summary>
    public class DataInitializer : IDataInitializer
    {
        /// <summary>
        /// 仓储中介者
        /// </summary>
        private readonly RepositoryMediator _repMediator;

        /// <summary>
        /// 单元事务
        /// </summary>
        private readonly IUnitOfWork _unitOfWork;

        /// <summary>
        /// 依赖注入构造器
        /// </summary>
        public DataInitializer(RepositoryMediator repMediator, IUnitOfWork unitOfWork)
        {
            this._repMediator = repMediator;
            this._unitOfWork = unitOfWork;
        }


        /// <summary>
        /// 初始化基础数据
        /// </summary>
        public void Initialize()
        {
            //注册获取用户信息事件
            EFUnitOfWorkProvider.GetLoginInfo += MembershipMediator.GetLoginInfo;

            //初始化OPC代理服务器
            this.InitOpcProxyServer();
        }

        /// <summary>
        /// 初始化OPC代理服务器
        /// </summary>
        private void InitOpcProxyServer()
        {
            if (!this._repMediator.OpcServerRep.Exists(Constants.OpcProxyServerId))
            {
                OpcServer opcProxyServer = new OpcServer("OPC代理服务器", OpcMode.UA, "opc.tcp://localhost:15511/ProxyServer", 10, 500, 5);
                opcProxyServer.SetId(Constants.OpcProxyServerId);

                this._unitOfWork.RegisterAdd(opcProxyServer);
                this._unitOfWork.Commit();
            }
        }
    }
}
